package com.knowledge.web.controller.system;

import java.util.*;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.knowledge.common.exception.ServiceException;
import com.knowledge.common.utils.*;
import com.knowledge.system.service.ISysUserService;
import com.knowledge.system.service.impl.SysUserServiceImpl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.knowledge.common.constant.Constants;
import com.knowledge.common.core.domain.AjaxResult;
import com.knowledge.common.core.domain.entity.SysMenu;
import com.knowledge.common.core.domain.entity.SysUser;
import com.knowledge.common.core.domain.model.LoginBody;
import com.knowledge.common.core.domain.model.LoginUser;
import com.knowledge.common.core.text.Convert;
import com.knowledge.framework.web.service.SysLoginService;
import com.knowledge.framework.web.service.SysPermissionService;
import com.knowledge.framework.web.service.TokenService;
import com.knowledge.system.service.ISysConfigService;
import com.knowledge.system.service.ISysMenuService;
import org.springframework.web.client.RestTemplate;

/**
 * 登录验证
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    //
//    /**
//     * 手机号登录方法
//     */
    @PostMapping("/loginByPhone")
    public AjaxResult loginByPhone(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String phonenumber = loginBody.getPhonenumber();
        // 先判断手机号是否存在
        List<SysUser> users = userService.selectUserByPhoneAndType(phonenumber, "01");
        SysUser sysUser = new SysUser();
        // 如果手机号不存在，先注册
        if (users == null || users.isEmpty()) {
            SysUser user = new SysUser();
            user.setPhonenumber(phonenumber);
            user.setUserName("user" + System.currentTimeMillis()); // 生成唯一的用户名
            user.setNickName("用户" + phonenumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")); // 脱敏处理
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setStatus("0"); // 正常状态
            user.setUserType("01");
//            user.setDeptId(100L); // 默认部门
//
//            // 设置默认角色
//            Long[] roleIds = {2L}; // 默认普通角色ID
//            user.setRoleIds(roleIds);
            userService.registerUser(user);
            List<SysUser> registerusers = userService.selectUserByPhoneAndType(phonenumber, "01");
            sysUser = registerusers.get(0);

        } else {
            sysUser = users.get(0);
        }
        // 修改为：
        LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = tokenService.createToken(loginUser);
        // 验证LoginUser中的用户信息是否完整
        if (loginUser.getUser().getUserId() == null) {
            return AjaxResult.error("登录用户信息不完整");
        }

        return AjaxResult.success("登录成功").put("token", token);
    }

    @Autowired
    private YzCodeUtils yzCodeUtils;


    private static String xcx_appId = "wxd265b1062d132455";
    private static String xcx_secretKey = "53528cc28706b1519ea92c2a1307cea9";

    /**
     * 微信小程序获取手机号登录
     */
    @PostMapping("/wechatLoginByPhoneNumber")
    public AjaxResult wechatLoginByPhoneNumber(@RequestBody LoginBody loginBody) throws Exception {
        String code = loginBody.getCode();
        String encryptedData = loginBody.getEncryptedData();
        String iv = loginBody.getIv();

        // 1. 参数校验
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("授权码不能为空");
        }
//        if (StringUtils.isEmpty(encryptedData)) {
//            return AjaxResult.error("加密数据不能为空");
//        }
//        if (StringUtils.isEmpty(iv)) {
//            return AjaxResult.error("初始向量不能为空");
//        }

        // 获取openId
        Map<String, String> wxOpenId = WxUtils.getWxOpenId(loginBody.getCode());
        String openId = wxOpenId.get("openId");
        String sessionKey = wxOpenId.get("sessionKey");
        if (StringUtils.isEmpty(openId)) {
            throw new ServiceException("openId获取失败");
        }
        String phoneNumber = WxUtils.getPhoneNumber(loginBody.getPhoneCode());
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException("手机号获取失败");
        }
        // 5. 查询用户是否存在
        List<SysUser> users = userService.selectUserByPhoneAndType(phoneNumber, "01");
        SysUser sysUser;

        // 6. 如果用户不存在则自动注册
        if (users == null || users.isEmpty()) {
            SysUser user = new SysUser();
            user.setPhonenumber(phoneNumber);
            user.setUserName("user" + System.currentTimeMillis());
            user.setNickName("用户" + phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setStatus("0");
            user.setUserType("01");
            userService.registerUser(user);
            // 重新查询注册后的用户
            List<SysUser> registerusers = userService.selectUserByPhoneAndType(phoneNumber, "01");
            sysUser = registerusers.get(0);
        } else {
            sysUser = users.get(0);
        }
        // 7. 构建登录用户对象并完成登录流程
        LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = tokenService.createToken(loginUser);
        return AjaxResult.success("登录成功").put("token", token);
    }


    /**
     * h5端 手机号+ 验证码登录，如果没有查询到手机号 ，提示注册
     */
    @PostMapping("/loginByPhoneAndCaptcha")
    public AjaxResult loginByPhoneAndCaptcha(@RequestBody LoginBody loginBody) {
        String phoneNumber = loginBody.getPhonenumber();
        String captcha = loginBody.getCode();

        // 1. 校验参数
        if (StringUtils.isEmpty(phoneNumber)) {
            return AjaxResult.error("手机号不能为空");
        }
        if (StringUtils.isEmpty(captcha)) {
            return AjaxResult.error("验证码不能为空");
        }

        String s = yzCodeUtils.checkRedisKey(phoneNumber, captcha);
        if (!StringUtils.isEmpty(s)) {
            return AjaxResult.error(s);
        }
        // 3. 查询用户是否存在
        List<SysUser> users = userService.selectUserByPhoneAndType(phoneNumber, "02");
        SysUser sysUser;

        if (users == null || users.isEmpty()) {
            // 4. 如果用户不存在，返回提示信息，引导前端跳转至注册页面
            return AjaxResult.error(2, "手机号尚未注册，请先注册");
        } else {
            sysUser = users.get(0);
        }

        // 5. 构建登录用户对象并完成登录流程
        LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = tokenService.createToken(loginUser);

        return AjaxResult.success("登录成功").put("token", token);
    }

    /**
     * h5端 手机号+ 密码登录
     */
    @PostMapping("/loginByPhoneAndPassword")
    public AjaxResult loginByPhoneAndPassword(@RequestBody LoginBody loginBody) {
        String phoneNumber = loginBody.getPhonenumber();
        String password = loginBody.getPassword();

        // 参数校验
        if (StringUtils.isEmpty(phoneNumber)) {
            return AjaxResult.error("手机号不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return AjaxResult.error("密码不能为空");
        }

        // 查询用户是否存在
        List<SysUser> users = userService.selectUserByPhoneAndType(phoneNumber, "02");
        if (users == null || users.isEmpty()) {
            return AjaxResult.error("用户不存在，请先注册");
        }

        SysUser sysUser = users.get(0);

        // 验证密码是否正确
        if (!SecurityUtils.matchesPassword(password, sysUser.getPassword())) {
            return AjaxResult.error("密码错误");
        }

        // 检查用户状态
        if (!"0".equals(sysUser.getStatus())) {
            return AjaxResult.error("用户账户已被禁用");
        }

        // 构建登录用户对象并完成登录流程
        LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = tokenService.createToken(loginUser);

        return AjaxResult.success("登录成功").put("token", token);
    }


    /**
     * h5端--用户注册 手机号、验证码、密码注册
     */
    @PostMapping("/registerByPhone")
    public AjaxResult registerByPhone(@RequestBody LoginBody loginBody) {
        String phoneNumber = loginBody.getPhonenumber();
        String captcha = loginBody.getCode();
        String password = loginBody.getPassword();

        // 参数校验
        if (StringUtils.isEmpty(phoneNumber)) {
            return AjaxResult.error("手机号不能为空");
        }
        if (StringUtils.isEmpty(captcha)) {
            return AjaxResult.error("验证码不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return AjaxResult.error("密码不能为空");
        }

        // 验证验证码
        String checkResult = yzCodeUtils.checkRedisKey(phoneNumber, captcha);
        if (!StringUtils.isEmpty(checkResult)) {
            return AjaxResult.error(checkResult);
        }

        // 检查手机号是否已注册
        List<SysUser> existingUsers = userService.selectUserByPhoneAndType(phoneNumber, "02");
        if (existingUsers != null && !existingUsers.isEmpty()) {
            return AjaxResult.error("该手机号已被注册");
        }

        // 创建新用户
        SysUser user = new SysUser();
        user.setPhonenumber(phoneNumber);
        user.setUserName("user" + System.currentTimeMillis()); // 生成唯一用户名
        user.setNickName("用户" + phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")); // 脱敏处理
        user.setPassword(SecurityUtils.encryptPassword(password)); // 加密密码
        user.setStatus("0"); // 正常状态
        user.setUserType("02"); // 普通用户类型

        // 注册用户
        userService.registerUser(user);
        return AjaxResult.success("注册成功");

    }


    /**
     * 微信登录
     */
    @PostMapping("/wechatLoginByOpenId")
    public AjaxResult wechatLoginByOpenId(String code) throws Exception {

        Map<String, String> wxOpenId = WxUtils.getWxOpenId(code);
        if (wxOpenId.get("openId") == null) {
            return AjaxResult.error("微信登录失败");
        }
        String openId = wxOpenId.get("openId");
        SysUser sysUser = userService.selectUserByOpenId(openId);
        if (sysUser == null) {
            // 未绑定账号
            return AjaxResult.error(1, openId);
        }
        LoginUser loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = tokenService.createToken(loginUser);
        return AjaxResult.success("登录成功").put("token", token);
    }

    /**
     * 微信openId 绑定到手机号中
     */
    @PostMapping("/wechatBangDingByPhone")
    public AjaxResult wechatBangDingByPhone(@RequestBody LoginBody loginBody) throws Exception {
        String openId = loginBody.getOpenId();
        String phonenumber = loginBody.getPhonenumber();

        // 参数校验
        if (StringUtils.isEmpty(openId)) {
            return AjaxResult.error("微信openId不能为空");
        }

        if (StringUtils.isEmpty(phonenumber)) {
            return AjaxResult.error("手机号不能为空");
        }

        // 检查手机号用户是否存在
        List<SysUser> phoneUsers = userService.selectUserByPhoneAndType(phonenumber, "01");
        SysUser phoneUser = new SysUser();

        if (phoneUsers == null || phoneUsers.isEmpty()) {
            SysUser user = new SysUser();
            user.setPhonenumber(phonenumber);
            user.setUserName("user" + System.currentTimeMillis()); // 生成唯一的用户名
            user.setNickName("用户" + phonenumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")); // 脱敏处理
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setStatus("0"); // 正常状态
            user.setUserType("01");
            userService.registerUser(user);
            List<SysUser> registerusers = userService.selectUserByPhoneAndType(phonenumber, "01");
            phoneUser = registerusers.get(0);
        } else {
            phoneUser = phoneUsers.get(0);
        }

        // 检查该手机号是否已经绑定了其他微信账号
        if (StringUtils.isNotEmpty(phoneUser.getOpenId()) && !openId.equals(phoneUser.getOpenId())) {
            return AjaxResult.error("该手机号已经绑定了其他微信账号");
        }

        // 更新用户信息，将openId绑定到手机号用户上
        phoneUser.setOpenId(openId);
        int result = userService.updateUserProfile(phoneUser);

        if (result > 0) {
            // 绑定成功后直接登录
            LoginUser loginUser = new LoginUser(phoneUser.getUserId(), phoneUser.getDeptId(), phoneUser, permissionService.getMenuPermission(phoneUser));
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phoneUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            String token = tokenService.createToken(loginUser);
            return AjaxResult.success("登录成功").put("token", token);
        } else {
            return AjaxResult.error("绑定失败");
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 判断密码是否修改
     *
     * @param pwdUpdateDate 上次修改时间
     * @return 结果
     */
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        return pwdUpdateDate != null && pwdUpdateDate.getTime() != 0;
    }

    /**
     * 判断密码是否过期
     *
     * @param pwdUpdateDate 上次修改时间
     * @return 结果
     */
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        // 登录时判断密码是否过期，过期时间365天
        return pwdUpdateDate != null && pwdUpdateDate.before(DateUtils.addDays(new Date(), -365));
    }
}
